package com.cetc;

import com.cetc.domain.Person;
import org.junit.Test;

import java.util.Random;

/**
 * @Classname NewInstanceTest
 * @Description 通过反射进行类的实例化
 * @Date 2022/11/29 20:40
 * @Created by louzhuangxi
 */
public class NewInstanceTest {
    /**
     * 创建Person类的对象
     */
    @Test
    public void test01() {
        Class<Person> clazz = Person.class;
        try {
            //newInstance调用了Person类的空参构造器
            Person person = clazz.newInstance();
            System.out.println(person);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test02() {
        for (int i = 0; i < 100; i++) {
            int num = new Random().nextInt(3);
            String class_path = "";
            switch (num) {
                case 0:
                    class_path = "java.util.Date";
                    break;
                case 1:
                    class_path = "java.lang.Object";
                    break;
                case 2:
                    class_path = "com.cetc.ClassLoaderTest";
                    break;
                default:
                    System.out.println("无此类，无法创建类的实例");
            }
            try {
                Object instance1 = getInstance(class_path);
                System.out.println(instance1.getClass().getName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取类的实例
     *
     * @param classPath 类的全路径限定名
     * @throws Exception
     */
    public Object getInstance(String classPath) throws Exception {
        Class<?> aClass = Class.forName(classPath);
        return aClass.newInstance();
    }
}
